import os
import sys
import re
import urllib2

class Route:
    def __init__(self):
        self.url = 'http://www.nextmuni.com/predictor/stopSelectorDataFrame.jsp?a=sf-muni'
        self.routeRegex = re.compile('.*?parent\.addOption\(routeSelector,\s+"(.*?)",\s+"(.*?)",(.*)', re.DOTALL)
        self.nameArr = []
        self.symbolArr = []

        self.loadRoutes()

    def parseRoute(self, htmlStr):
        m = self.routeRegex.match(htmlStr)

        if (m == None):
            return (None, None, None)

        return (m.group(1), m.group(2), m.group(3))

    def loadRoutes(self):
        req = urllib2.Request(self.url)
        response = urllib2.urlopen(req)
        htmlStr = response.read()

        self.nameArr = []
        self.symbolArr = []
        
        (name, symbol, restOfHtmlStr) = self.parseRoute(htmlStr)
        while (restOfHtmlStr != None):
            self.nameArr.append(name)
            self.symbolArr.append(symbol)
            
            (name, symbol, restOfHtmlStr) = self.parseRoute(restOfHtmlStr) 

    def getName(self, symbol):
        for i in range(0, len(self.symbolArr)):
            currSymbol = self.symbolArr[i]
            if (currSymbol == symbol):
                return self.nameArr[i]

        return None

    def getSymbol(self, name):
        for i in range(0, len(self.nameArr)):
            currName = self.nameArr[i]
            if (currName == name):
                return self.symbolArr[i]

        return None


            
